<?php
	$airmonths = array("","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	$oldmovie = "";
	$olddir = "";
	$tvxml = "";
	$imdbnr = 0;
	$movtypes = array("mov","avi","mpg","mpeg","divx","ogm","mkv","mp4","m4v","mp4v");
//	$file = "Battlestar.Galactica.S1.E10.The.Hand.of.God.DVDRip.Divx";
//	$file = "heroes.121.hdtv-lol.avi";
//	$file = "Megas XLR - 2x06 Space Booty [Moonsong].avi";

	$series = array();

	if(isset($argv[1]) and file_exists($argv[1])){
		processdir($argv[1]);
//		$moviedir = substr($argv[1], 0, strrpos($argv[1],"/")+1);
//		$file = substr($argv[1],strrpos($argv[1],"/")+1);

//		processfile($moviedir, $file);

		print_r($series);
	}else{
		die("\nUsage: php series.php <path_to_movie> <download_subtitles 1|0>\n\n");
	}


	function processdir($dir){
		$mdir = opendir($dir);
		while(false !== ($f = readdir($mdir))){
			if(substr($f,0,1) == "."){ continue; }
			if(is_dir($dir.$f)){
				processdir($dir.$f."/");
			}else{
				$ext = strtolower(substr($f, strrpos($f, ".")+1));
				if($ext == "avi"){
					processfile($dir,$f);
				}
			}
		}
	}


	function processfile($dir, $file){
		echo "Processing $file\n";
		global $airmonths, $oldmovie, $movtypes, $tvxml, $olddir, $imdbnr, $argv, $series;
			$ext = strtolower(substr($file, strrpos($file, ".")+1));

			$matches = array();
			if(preg_match("/(.+?)\Ds(\d+)\.?e(\d+?)\.(\D+)\./i", $file, $matches)){
//				echo "version 1...\n";
				$episode = round($matches[3]);
				$season  = round($matches[2]);
				$release = $matches[4];
				$title   = str_replace("."," ",$matches[1]);
			}elseif(preg_match("/(.+?)\Ds(\d+)\.?x(\d+?)\.(\D+)\./i", $file, $matches)){
//				echo "version 2...\n";
				$episode = round($matches[3]);
				$season  = round($matches[2]);
				$release = $matches[4];
				$title   = str_replace("."," ",$matches[1]);
			}elseif(preg_match("/(.+?)\D(\d+)x(\d+)\.(\D+)\./i", $file, $matches)){
//				echo "version 3...\n";
				$episode = round($matches[3]);
				$season  = round($matches[2]);
				$release = $matches[4];
				$title   = str_replace("."," ",$matches[1]);
			}elseif(preg_match("/(.+?)\D(\d+)\.(\D+)\./", $file, $matches)){
//				echo "version 5...\n";
//				print_r($matches);
				$episode = round(substr($matches[2],1));
				$season  = round(substr($matches[2],0,1));
				$release = $matches[3];
				$title   = str_replace("."," ",$matches[1]);
			}elseif(preg_match("/(\d+?) - ([\w\s]+) - /", $file, $matches)){
//				echo "version 6...\n";
				$episode = round(substr($matches[1],1));
				$season  = 1;
				$title   = str_replace("."," ",$matches[2]);
				$release = "none";
			}
			
			echo " - ".$title." - ".$season."x".$episode."\n";
			$temp = get_show($title,0, $season."x".$episode);
			echo " - Got show info\n";

			$title = substr($temp[5],strpos($temp[5], "\"")+1);
			$title = substr($title, 0, strpos($title, "\""));

			$airdate = explode("/",trim(substr($temp[5], strpos($temp[5], "aired on ")+10)));
			$airdate = $airdate[2]."-".array_search($airdate[1],$airmonths)."-".$airdate[0];

			$genres = explode(" | ",trim($temp[10]));

			if(isset($temp[6]) and ($temp[6] != "")){
				$episodepage = implode("",file($temp[6]));
				$episodeinfo = substr($episodepage, strpos($episodepage, "<td align='center'><font size='2'><b>Episode Summary</b></font></td>"), strpos($episodepage, "<td align='center'><font size='2'><b>Guest Stars</b></font></td>")-strpos($episodepage, "<td align='center'><font size='2'><b>Episode Summary</b></font></td>"));
				$episodeinfo = substr($episodeinfo, strpos($episodeinfo, "<table width='100%'><tr><td>")+strlen("<table width='100%'><tr><td>"));
				$episodeinfo = substr($episodeinfo, 0, strpos($episodeinfo, "</td>"));
				$episodeinfo = strip_tags($episodeinfo);
				$episodeinfo = trim(str_replace("&nbsp;"," ",$episodeinfo));
				echo " - Grabbed episode description\n";
			}
			$publisher = trim($temp[11]);
			$movie = trim($temp[0]);


			if(!isset($series[trim($temp[0])])){
				$series[trim($temp[0])] = array(
					"publisher"=>$publisher,
					"seasons"=>array()
				);
			}
			if(!isset($series[trim($temp[0])]["seasons"][$season])){
				$series[trim($temp[0])]["seasons"][$season] = array();
			}
			$series[trim($temp[0])]["seasons"][$season][$episode] = array("descr"=>$episodeinfo,"airdate"=>$airdate,"title"=>$title);
/*
				$xml = '<media type="TV Show">
	<title>'.sprintf("%02s",$episode).". ".$title.'</title>
	<description>'.str_replace("\n\n","\n",$episodeinfo).'</description>
	<publisher>'.$publisher.'</publisher>
	<copyright>Copyright '.trim($temp[2]).' '.$publisher.'</copyright>
	<seriesName>'.trim($temp[0]).'</seriesName>
	<broadcaster>'.$publisher.'</broadcaster>
	<episodeNumber>'.$season.$episode.'</episodeNumber>
	<episode>'.$episode.'</episode>
	<season>'.$season.'</season>
	<published>'.$airdate.'</published>
'.$tvxml.'
</media>
';
*/
			}

	exit;



function get_show($show,$exact="",$episode="") {

if ( !$show ) { return FALSE; }

if ( $fp = fopen("http://www.tvrage.com/quickinfo.php?show=".urlencode($show)."&ep=".urlencode($episode)."&exact=".urlencode($exact),"r") )
  {
  while ( !feof($fp))
    {
    $line = fgets($fp,1024);
    list ($sec,$val) = explode('@',$line,2);
    if ($sec == "Show Name" )
      {
      $ret[0] = $val;
      }
    elseif ( $sec == "Show URL" )
      {
      $ret[1] = $val;
      }
    elseif ( $sec == "Premiered" )
      {
      $ret[2] = $val;
      }
    elseif ($sec == "Country" )
      {
      $ret[7] = $val;
      }
    elseif ( $sec == "Status" )
      {
      $ret[8] = $val;
      }
    elseif ( $sec == "Classification" )
      {
      $ret[9] = $val;
      }
    elseif ( $sec == "Genres" )
      {
      $ret[10] = $val;
      }
    elseif ( $sec == "Network" )
      {
      $ret[11] = $val;
      }
    elseif ( $sec == "Airtime" )
      {
      $ret[12] = $val;
      }

    elseif ( $sec == "Latest Episode" )
      {
      list ($ep,$title,$airdate) = explode('^',$val);
      $ret[3] = $ep.", \"".$title."\" aired on ".$airdate;
      }
    elseif ( $sec == "Next Episode" )
      {
      list ($ep,$title,$airdate) = explode('^',$val);
      $ret[4] = $ep.", \"".$title."\" airs on ".$airdate;
      }
    elseif ( $sec == "Episode Info" )
      {
      list ($ep,$title,$airdate) = explode('^',$val);
      $ret[5] = $ep.", \"".$title."\" aired on ".$airdate;
      }
    elseif ( $sec == "Episode URL" )
      {
      $ret[6] = $val;
      }
    }
  fclose($fp);
  if ( $ret[0] )
    {
    return $ret;
    }
  }
else
  {
  return FALSE;
  }
}


?>
